/**
 * @class yijs.air.Db
 * @fileOverview sqlite数据库操作类
 * @author 谢文浩
 * @email mohaiguyan12@126.com
 * @version 0.11
 * @date 2010-01-26
 * Copyright (c) 2010-2010 谢文浩
 */
var yijs = yijs || {};
yijs.air = {};
yijs.air.Db = function(url,mode,isAsync){
	this.url = url;
	this.mode = mode || air.SQLMode.UPDATE;
	this.isAsync = isAsync || false;
	this.listeners = {
		open :null
	}
	this.reset();
}
yijs.air.Db.prototype = {
		/**
		 * 创建数据库连接
		 */	
		createConnection : function(){
			var _that = this;
			this.Conn = new air.SQLConnection();
			this.DbFile = new air.File(this.url);
			if(this.isAsync){
				this.Conn.addEventListener(air.SQLEvent.OPEN,function(){
					if(_that.listeners.open != null) _that.listeners.open.call(this);
				});
				this.Conn.openAsync(this.DbFile);
			}else{
				try{
					this.Conn.open(this.DbFile,this.mode);
					if(_that.listeners.open != null) _that.listeners.open.call(this);				
				}catch(error){
					alert("异常信息："+error.message+",详细内容："+error.details);
				}				
			}			
		},
		/**
		 * 创建sql
		 * @param {String} sqlText sql语句
		 */
		_createSQL : function(sqlText){
			var sql = new air.SQLStatement();
			sql.sqlConnection = this.Conn;
			sql.text = sqlText;	
			sql.execute();
			this.Conn.close();
			return sql;
		},
		/**
		 * 向表插入数据
		 * @param {String} table 数据表
		 * @param {Object} data  数据
		 * @return {Number} id 插入的数据在数据库中的索引
		 */			
		insert : function(table,data){
			var _that = this;
			if(table && data){
				this.createConnection();
				var sqlText = "INSERT INTO "+table+" ";
				var keys = [];
				var values = [];
				$.each(data,function(key,value){
					keys.push(key);
					var val = _that._formatValue(value);
					values.push(val);
				});
				sqlText += " ("+keys.join(",")+") ";
				sqlText += "VALUES ";
				sqlText += "("+values.join(",")+")";
				var Sql = this._createSQL(sqlText);	
				var result = Sql.getResult();
				this.reset();
				return result.lastInsertRowID;				
			}
			return -1;
		},
		/**
		 * 数据库操作条件，共有三种模式，值对、对象字面量、条件字符串,生成的条件以AND连接
		 * @param {String/Object} keyOrDataOrString  条件
		 * @param {Object} value 值对模式中的值
		 */			
		where : function(keyOrDataOrString,value){
			this._setWhere(keyOrDataOrString,value," AND ");
			return this;
		},
		/**
		 * 数据库操作条件，共有三种模式，值对、对象字面量、条件字符串,生成的条件以OR连接
		 * @param {String/Object} keyOrDataOrString  条件
		 * @param {Object} value 值对模式中的值
		 */			
		orWhere : function(keyOrDataOrString,value){
			this._setWhere(keyOrDataOrString,value," OR ");
			return this;			
		},
		orderby : function(key,value){
			var _v = key + " " + value.toUpperCase();
			this.strOrderby += this.strOrderby == "" && " ORDER BY "+ _v || ","+_v;
			return this;
		},
		limit : function(startOrnum,num){
			this.strLimit = num && " LIMIT " + startOrnum + "," + num || " LIMIT " + "0," + startOrnum;
			return this;
		},
		/**
		 * 允许你在SQL查询中写 SELECT 部分
		 * @param {String} Str 
		 */		
		select : function(Str){
			if(Str){
				this.strSelect = this.strSelect == "" && "SELECT "+ Str || this.strSelect+","+ Str;
			}
			return this;
			
		},		
		/**
		 * 获取数据表数据
		 * @param {String} table 数据表
		 */
		get : function(table){
			if(table){
				this.createConnection();
				sqlText = this.strSelect == "" && "SELECT * " || this.strSelect;
				sqlText += " FROM "+table;
				if (this.strWhere != "") {
					sqlText += " WHERE " + this.strWhere;
				}
				if(this.strOrderby != "") sqlText += this.strOrderby;
				if(this.strLimit != "") sqlText += this.strLimit;
				var Sql = this._createSQL(sqlText);	
				this.reset();
				return Sql.getResult();				
			}
		},
		/**
		 * 删除表中的指定数据
		 * @param {String} table 数据表
		 * @param {Object} data  删除的条件
		 */			
		del : function(table){
			if(table){
				this.createConnection();
				//var andOr = andOr || "and";
				if(this.strWhere != ""){
					var where = " WHERE " + this.strWhere;
					var sqlText = "DELETE FROM "+table+" "+where;
					var Sql = this._createSQL(sqlText);	
					this.reset();					
				}
				//where += andOr == "and" && this.where(data) || this.orWhere(data);
				//alert(where);
				
				return true;					
			}
		},
		/**
		 * 更新表数据
		 * @param {String} table 数据表
		 * @param {Object} data  数据
		 */			
		update : function(table,data){
			if(table && data){
				var _that = this;
				this.createConnection();
				var where = this.strWhere != "" && " WHERE " + this.strWhere || "";
				var sets = [];
				$.each(data,function(key,value){
					var val = _that._formatValue(value);
					sets.push(""+key+"="+val+"");
				});			
				var sqlText = "UPDATE "+table+" SET "+sets.join(",")+" "+where;
				var Sql = this._createSQL(sqlText);	
				this.reset();					
			}
		},						
		/**
		 * sql执行完毕进行重置
		 */			
		reset : function(){
			this.strWhere = "";
			this.strSelect = "";
			this.strOrderby = "";
			this.strLimit = "";
		},	
		/**
		 * 绑定事件
		 * @param {string} type
		 * @param {Object} fn
		 */
		bind : function(type,fn){
			this.listeners[type] = fn;
		},
		/**
		 * 移除事件
		 * @param {string} type
		 * @param {Object} fn
		 */
		unbind : function(type,fn){
			this.listeners[type] = null;
		},			
		/**
		 * 格式化sql语句中的值
		 */
		_formatValue : function(value){
			if(typeof value == "number" || typeof value == "boolean"){
				return value;
			}else if(typeof value == "string"){
				return "'"+value+"'";
			}else{
				return value;
			}
		},
		/**
		 * 对where中的值对进行处理
		 */
		_setKeyValue : function(key,value){
			var _s = "";
			var reg = /[!=<>]/;
			var value = this._formatValue(value);
			if(reg.test(key)){
				_s = key +" "+ value;
			}else{
				_s = key + "=" + value;
			}
			return _s;
		},
		/**
		 * 处理where语句
		 */		
		_setWhere : function(keyOrDataOrString,value,joint){
			var _s = " ";
			var _that = this;
			if(this.strWhere != "") _s = joint;
			if(typeof keyOrDataOrString == "string"){
				if(value){
					var reg = /[!=<>]/;
					_s += this._setKeyValue(keyOrDataOrString,value);
				}else{
                    _s += keyOrDataOrString;
				}
			}else if(typeof keyOrDataOrString == "object"){
				var _a = [];
				$.each(keyOrDataOrString,function(key,val){
					_a.push(_that._setKeyValue(key,val));
				})
				_s += _a.join(joint);
			}
			this.strWhere += _s;
			return _s;
		}
}